﻿namespace MDK.Common
{
    public static class BytesExtensions
    {
        public static byte[] SetCrc16(this byte[] data)
        {
            var len = data.Length - 2;
            if (len > 0)
            {
                ushort crc = 0xFFFF;

                for (var i = 0; i < len; i++)
                {
                    crc = (ushort)(crc ^ (data[i]));
                    for (var j = 0; j < 8; j++)
                    {
                        crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
                    }
                }
                data[data.Length - 1] = (byte)((crc & 0xFF00) >> 8);  //高位置
                data[data.Length - 2] = (byte)(crc & 0x00FF);         //低位置
            }
            return data;
        }

        public static byte[] PackModbus(this byte[] cmdBuf, int value)
        {
            cmdBuf[10] = (byte)((value >> 8) & 0xff);
            cmdBuf[11] = (byte)(value & 0xff);
           // cmdBuf.SetCrc16();
            return cmdBuf;
        }

        public static byte[] PackModbus(this byte[] cmdBuf, int value, int addr)
        {
            cmdBuf[2] = (byte) ((addr >> 8) & 0xff);
            cmdBuf[3] = (byte) (addr & 0xff);
            return cmdBuf.PackModbus(value);
        }
    }
}